from flask import Blueprint, render_template, request, flash, redirect, url_for
from models import db, User, Role, Permission
from auth import login_required, permission_required

admin_bp = Blueprint('admin', __name__, url_prefix='/admin')

@admin_bp.route('/')
@login_required
@permission_required('manage_users')
def index():
    users = User.query.all()
    return render_template('admin/index.html', users=users)

@admin_bp.route('/users')
@login_required
@permission_required('manage_users')
def users():
    users = User.query.all()
    return render_template('admin/users.html', users=users)

@admin_bp.route('/users/add', methods=['GET', 'POST'])
@login_required
@permission_required('manage_users')
def add_user():
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        role_ids = request.form.getlist('roles')
        
        if User.query.filter_by(username=username).first():
            flash('用户名已存在', 'danger')
            return redirect(url_for('admin.add_user'))
            
        user = User(username=username)
        user.set_password(password)
        
        for role_id in role_ids:
            role = Role.query.get(role_id)
            if role:
                user.roles.append(role)
                
        db.session.add(user)
        db.session.commit()
        flash('用户添加成功', 'success')
        return redirect(url_for('admin.users'))
        
    roles = Role.query.all()
    return render_template('admin/add_user.html', roles=roles)

@admin_bp.route('/users/<int:user_id>/edit', methods=['GET', 'POST'])
@login_required
@permission_required('manage_users')
def edit_user(user_id):
    user = User.query.get_or_404(user_id)
    if request.method == 'POST':
        username = request.form['username']
        role_ids = request.form.getlist('roles')
        
        if username != user.username and User.query.filter_by(username=username).first():
            flash('用户名已存在', 'danger')
            return redirect(url_for('admin.edit_user', user_id=user_id))
            
        user.username = username
        user.roles = []
        
        for role_id in role_ids:
            role = Role.query.get(role_id)
            if role:
                user.roles.append(role)
                
        db.session.commit()
        flash('用户更新成功', 'success')
        return redirect(url_for('admin.users'))
        
    roles = Role.query.all()
    return render_template('admin/edit_user.html', user=user, roles=roles)

@admin_bp.route('/users/<int:user_id>/deactivate')
@login_required
@permission_required('manage_users')
def deactivate_user(user_id):
    user = User.query.get_or_404(user_id)
    user.is_active = False
    db.session.commit()
    flash('用户已禁用', 'success')
    return redirect(url_for('admin.users'))

@admin_bp.route('/users/<int:user_id>/activate')
@login_required
@permission_required('manage_users')    
def activate_user(user_id):
    user = User.query.get_or_404(user_id)
    user.is_active = True
    db.session.commit()
    flash('用户已激活', 'success')
    return redirect(url_for('admin.users'))


@admin_bp.route('/users/<int:user_id>/delete')
@login_required
@permission_required('manage_users')
def delete_user(user_id):
    user = User.query.get_or_404(user_id)
    db.session.delete(user)
    db.session.commit()
    flash('用户删除成功', 'success')
    return redirect(url_for('admin.users'))

@admin_bp.route('/roles')
@login_required
@permission_required('manage_roles')
def roles():
    roles = Role.query.all()
    return render_template('admin/roles.html', roles=roles)

@admin_bp.route('/roles/add', methods=['GET', 'POST'])
@login_required
@permission_required('manage_roles')
def add_role():
    if request.method == 'POST':
        name = request.form['name']
        description = request.form['description']
        permission_ids = request.form.getlist('permissions')
        
        if Role.query.filter_by(name=name).first():
            flash('角色名已存在', 'danger')
            return redirect(url_for('admin.add_role'))
            
        role = Role(name=name, description=description)
        
        for permission_id in permission_ids:
            permission = Permission.query.get(permission_id)
            if permission:
                role.permissions.append(permission)
                
        db.session.add(role)
        db.session.commit()
        flash('角色添加成功', 'success')
        return redirect(url_for('admin.roles'))
        
    permissions = Permission.query.all()
    return render_template('admin/add_role.html', permissions=permissions)

@admin_bp.route('/roles/<int:role_id>/edit', methods=['GET', 'POST'])
@login_required
@permission_required('manage_roles')
def edit_role(role_id):
    role = Role.query.get_or_404(role_id)
    if request.method == 'POST':
        name = request.form['name']
        description = request.form['description']
        permission_ids = request.form.getlist('permissions')
        
        if name != role.name and Role.query.filter_by(name=name).first():
            flash('角色名已存在', 'danger')
            return redirect(url_for('admin.edit_role', role_id=role_id))
            
        role.name = name
        role.description = description
        role.permissions = []
        
        for permission_id in permission_ids:
            permission = Permission.query.get(permission_id)
            if permission:
                role.permissions.append(permission)
                
        db.session.commit()
        flash('角色更新成功', 'success')
        return redirect(url_for('admin.roles'))
        
    permissions = Permission.query.all()
    return render_template('admin/edit_role.html', role=role, permissions=permissions)

@admin_bp.route('/roles/<int:role_id>/delete')
@login_required
@permission_required('manage_roles')
def delete_role(role_id):
    role = Role.query.get_or_404(role_id)
    db.session.delete(role)
    db.session.commit()
    flash('角色删除成功', 'success')
    return redirect(url_for('admin.roles'))

@admin_bp.route('/permissions')
@login_required
@permission_required('manage_permissions')
def permissions():
    permissions = Permission.query.all()
    return render_template('admin/permissions.html', permissions=permissions)

@admin_bp.route('/permissions/add', methods=['GET', 'POST'])
@login_required
@permission_required('manage_permissions')
def add_permission():
    if request.method == 'POST':
        name = request.form['name']
        description = request.form['description']
        
        if Permission.query.filter_by(name=name).first():
            flash('权限名已存在', 'danger')
            return redirect(url_for('admin.add_permission'))
            
        permission = Permission(name=name, description=description)
        db.session.add(permission)
        db.session.commit()
        flash('权限添加成功', 'success')
        return redirect(url_for('admin.permissions'))
        
    return render_template('admin/add_permission.html')

@admin_bp.route('/permissions/<int:permission_id>/edit', methods=['GET', 'POST'])
@login_required
@permission_required('manage_permissions')
def edit_permission(permission_id):
    permission = Permission.query.get_or_404(permission_id)
    if request.method == 'POST':
        name = request.form['name']
        description = request.form['description']
        
        if name != permission.name and Permission.query.filter_by(name=name).first():
            flash('权限名已存在', 'danger')
            return redirect(url_for('admin.edit_permission', permission_id=permission_id))
            
        permission.name = name
        permission.description = description
        db.session.commit()
        flash('权限更新成功', 'success')
        return redirect(url_for('admin.permissions'))
        
    return render_template('admin/edit_permission.html', permission=permission)

@admin_bp.route('/permissions/<int:permission_id>/delete')
@login_required
@permission_required('manage_permissions')
def delete_permission(permission_id):
    permission = Permission.query.get_or_404(permission_id)
    db.session.delete(permission)
    db.session.commit()
    flash('权限删除成功', 'success')
    return redirect(url_for('admin.permissions')) 